//
//  mainViewController.m
//  天气预报
//
//  Created by 娟娟 on 15/9/18.
//  Copyright (c) 2015年 wang. All rights reserved.
//

#import "mainViewController.h"
#import "LBBlurredImage/UIImageView+LBBlurredImage.h"
#import "Masonry.h"
#import "OpenWeatherMapInterface.h"
#import "TableViewCell.h"
#import "CBChartView.h"
#import "ThreeHoursData.h"
#import "addCityViewController.h"
#import "cityListViewController.h"
#import <sqlite3.h>

#define _height self.view.frame.size.height
#define _width self.view.frame.size.width

@interface mainViewController ()
@property (strong,nonatomic)UIImageView *blurredView;
@property (strong,nonatomic)UITableView *tableView;
@property (strong,nonatomic)UIScrollView *scrollView;

@property (strong,nonatomic)CurrentWeatherData * weatherCurrentData;
@property (strong,nonatomic)NSMutableArray *hoursTempreture;
@property (strong,nonatomic)NSMutableArray *daysTempreture;
@property (strong,nonatomic)NSString *intString;

//背景图片的轮流播放
@property(nonatomic,strong) NSTimer *timer;
@property(nonatomic,strong) UIImageView *backGround;

//滑动手势和分页控制
@property(nonatomic,strong) UISwipeGestureRecognizer *recognizerRight;
@property(nonatomic,strong) UISwipeGestureRecognizer *recognizerLeft;
@property(nonatomic,strong) UIPageControl *pg;

//首页的布局控件
@property(nonatomic,strong) UILabel *cityname;
@property(nonatomic,strong) UIImageView *weatherImage;
@property(nonatomic,strong) UILabel *weatherLabel;
@property(nonatomic,strong) UILabel *currentTempretureLabel;
@property(nonatomic,strong) UILabel *tempretureRangeLabel;
@property(nonatomic,strong) UILabel *lb1;
@end
static NSString *Cell = @"TableViewCell";
@implementation mainViewController
 

//判断手势，以及切换页面，但是是否需要将那个全局数组置空再入栈？？？
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    // NSLog(@"%@",self.navigationController.viewControllers[0]);
 
    if (item.tag ==0) {
        AppDelegate *appDelegate= [[UIApplication sharedApplication]delegate];
        if(appDelegate.citys.count<5)
        {
        //如果不重新新建的话，会出现问题
        cityListViewController *cityVC = [[cityListViewController alloc]initWithNibName:@"cityListViewController" bundle:nil];
        [self.navigationController pushViewController:
         cityVC animated:YES];
        }
        else
        {
            MBProgressHUD *HUD = [[MBProgressHUD alloc]initWithView:self.view];
            [self.view addSubview:HUD];
            HUD.labelText = @"不能多于五个城市啦~~~要不删除一个~？O(∩_∩)O~";
            HUD.mode = MBProgressHUDModeCustomView;
            [HUD showAnimated:YES whileExecutingBlock:^{
                sleep(2);
            } completionBlock:^{
                [HUD removeFromSuperview];
            }];
        }
    }
    if (item.tag == 2) {
      addCityViewController *addCity = [[addCityViewController alloc]initWithNibName:@"addCityViewController" bundle:nil];
      [self.navigationController pushViewController:addCity animated:YES];
    }
}

//手势处理函数
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recongnizer
{
    int page = self.pg.currentPage ;
    if (recongnizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        page--;
        if (page<0) return;
        self.pg.currentPage = page;
        
    }
    if (recongnizer.direction == UISwipeGestureRecognizerDirectionRight) {
        page++;
        if (page >4) return;
        self.pg.currentPage = page;
        
    }
    AppDelegate *appDelegate= [[UIApplication sharedApplication]delegate];
    self.cityName = appDelegate.citys[self.pg.currentPage];
    [self getWeatherDataByCityname:self.cityName];
    [self setTheCurrentMessage:self.weatherCurrentData];
    [self.tableView reloadData];
}

//根据传入的城市名获得相应的数据
-(void)getWeatherDataByCityname:(NSString *)cityname
{
    self.weatherCurrentData=[OpenWeatherMapInterface getCurrentDataWithCityName:cityname  andCountryCode:nil];
    self.hoursTempreture=[OpenWeatherMapInterface getOneDayWwatherDataWithCityName:cityname andCountryCode:nil];
    self.daysTempreture = [OpenWeatherMapInterface getFifteenDayWwatherDataWithCityName:cityname andCountryCode:nil];
}
//当一开始没有关注的城市的时候，点击加入城市-----同样，入栈之前是否需要清空栈
-(void)btnClicked
{
    cityListViewController *cityVC = [[cityListViewController alloc]initWithNibName:@"cityListViewController" bundle:nil];
    [self.navigationController pushViewController:cityVC animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.recognizerRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    self.recognizerLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [self.recognizerLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.view addGestureRecognizer:self.recognizerLeft];
    [self.recognizerRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:self.recognizerRight];
    AppDelegate *appDelegate= [[UIApplication sharedApplication]delegate];
     if(appDelegate.citys.count==0)
     {
         //整体布局
         UIImage * backgroundImage = [UIImage imageNamed:@"bg33"];
         // Do any additional setup after loading the view, typically from a nib.
         self.backGround =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _width,_height )];
         self.backGround.image = backgroundImage;
         [self.view addSubview:self.backGround];
         
         self.backGround.contentMode=UIViewContentModeScaleAspectFill;
         //模糊视图
         self.blurredView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _width,_height )];
         [self.blurredView setImageToBlur:backgroundImage blurRadius:10 completionBlock:nil];
         self.blurredView.alpha =0;
         [self.backGround addSubview:self.blurredView];
         
         UIButton  *btn = [[UIButton alloc]init];
         [btn setTitle:@"主人，添加一个城市啦~~~" forState:UIControlStateNormal];
         btn.frame  = CGRectMake(0, 100, 300, 40);
         [btn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchDown];
         [self.view addSubview:btn];
     }
     else
     {
         if(self.selectedCityName == NULL)
         self.cityName = [appDelegate.citys lastObject];
         else
             self.cityName = self.selectedCityName;
         self.weatherCurrentData =[[CurrentWeatherData alloc]init];
         [self getWeatherDataByCityname:self.cityName];
         [self setAllLayOut];
         UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];
         [self.tableView registerNib:nib forCellReuseIdentifier:Cell];
         [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
     }
}

#pragma mark - AllLayout
//设置整体布局
-(void)setAllLayOut
{
    //整体布局
    UIImage * backgroundImage = [UIImage imageNamed:@"bg11.jpg"];
    // Do any additional setup after loading the view, typically from a nib.
    self.backGround =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _width,_height )];
    self.backGround.image = backgroundImage;
    [self.view addSubview:self.backGround];
    
    self.backGround.contentMode=UIViewContentModeScaleAspectFill;
    //模糊视图
    self.blurredView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _width,_height )];
    [self.blurredView setImageToBlur:backgroundImage blurRadius:10 completionBlock:nil];
    self.blurredView.alpha =0;
    [self.backGround addSubview:self.blurredView];
    
    //滚动图
    //self.scrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, _width,_height)];
    self.scrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, _width,_height)];
    self.scrollView.backgroundColor=[UIColor clearColor];
    self.scrollView.contentSize=CGSizeMake(_width, _height*4);
    self.scrollView.scrollEnabled=YES;
    self.scrollView.pagingEnabled=YES;
    self.scrollView.delegate=self;
    [self.view addSubview:self.scrollView];
    float maxTem =-100;
    float minTem =100;
   
    CBChartView *chartView = [[CBChartView alloc]init];
    chartView.shutDefaultAnimation = YES;
    [self.scrollView addSubview:chartView];
    NSRange rangeTime = NSMakeRange(11, 2);
    NSMutableArray *xValueArr=[[NSMutableArray alloc]init];
    NSMutableArray *yValueArr=[[NSMutableArray alloc]init];
 
    for (ThreeHoursData * temp in self.hoursTempreture) {
        [xValueArr addObject:[temp.date  substringWithRange:rangeTime]];
        [yValueArr addObject:[temp.temperature stringValue]];
        if (maxTem<[temp.temperature floatValue]) {
            maxTem=[temp.temperature floatValue];
        }
        if (minTem>[temp.temperature floatValue]) {
            minTem=[temp.temperature floatValue];
        }
    }
    
    UILabel *lab = [[UILabel alloc]init];
    lab.text = [NSString stringWithFormat:@"%d",[yValueArr[0]integerValue]];
    lab.frame = CGRectMake( 160, 320-(10*[yValueArr[0]floatValue ])-10, 20 , 20 );
    lab.textColor = [UIColor redColor];
    
    UILabel *lab1 = [[UILabel alloc]init];
    lab1.text = [NSString stringWithFormat:@"%d",[yValueArr[1]integerValue]];
    //lab1.text = yValueArr[1];
    //lab1.frame = CGRectMake( 190, chartView.frame.origin.y +40, 20 , 20 );
    lab1.frame = CGRectMake( 190, 320-(10*[yValueArr[1]floatValue ]), 20 , 20 );
    
    lab1.textColor = [UIColor redColor];
    UILabel *lab2 = [[UILabel alloc]init];
    lab2.text = [NSString stringWithFormat:@"%d",[yValueArr[2]integerValue]];
    //lab1.text = yValueArr[1];
    //lab1.frame = CGRectMake( 190, chartView.frame.origin.y +40, 20 , 20 );
    //lab2.frame = CGRectMake(210, 320-(10*[yValueArr[2]floatValue ]), 20 , 20 );
    float nnn = [yValueArr[2] floatValue];
    nnn = 300*nnn;
    nnn = nnn/32;
    nnn = 320-510+nnn;
    lab2.frame = CGRectMake(240, nnn, 20, 20);
    lab2.textColor = [UIColor redColor];
    
    UILabel *lab3 = [[UILabel alloc]init];
    lab3.text = [NSString stringWithFormat:@"%d",[yValueArr[3]integerValue]];
    
    //lab1.text = yValueArr[1];
    //lab1.frame = CGRectMake( 190, chartView.frame.origin.y +40, 20 , 20 );
    lab3.frame = CGRectMake( 260, 320-(10*[yValueArr[3]floatValue ])-30, 20 , 20 );
    
    lab3.textColor = [UIColor redColor];
    UILabel *lab4 = [[UILabel alloc]init];
    lab4.text = [NSString stringWithFormat:@"%d",[yValueArr[4]integerValue]];
    //lab1.text = yValueArr[1];
    //lab1.frame = CGRectMake( 190, chartView.frame.origin.y +40, 20 , 20 );
    lab4.frame = CGRectMake( 300, 320-(10*[yValueArr[4]floatValue ])-30, 20 , 20 );
    
    lab4.textColor = [UIColor redColor];
   
    
    UILabel *lab5 = [[UILabel alloc]init];
    lab5.text = [NSString stringWithFormat:@"%d",[yValueArr[5]integerValue]];
    
    //lab1.text = yValueArr[1];
    //lab1.frame = CGRectMake( 190, chartView.frame.origin.y +40, 20 , 20 );
    lab5.frame = CGRectMake( 340, 320-(10*[yValueArr[4]floatValue ])-30, 20 , 20 );
    
    lab5.textColor = [UIColor redColor];
    
    
    [chartView addSubview:lab5];

    
    [chartView addSubview:lab4];

    
    [chartView addSubview:lab];
    
    [chartView addSubview:lab1];
    [chartView addSubview:lab2];
     [chartView addSubview:lab3];
    
    chartView.xValues = xValueArr;
    chartView.yValues = yValueArr;
    
    chartView.chartWidth = 2.0;
    chartView.chartColor = [UIColor whiteColor];
    //chartView.isDrawDashLine = NO;
    
    [UIView animateWithDuration:1 animations:^{
        //chartView.frame = CGRectMake(-150, 110, 400, 320);
        chartView.frame = CGRectMake(-110, 60, 400, 320);
    }];
    /*
    for(i=0;i<xValueArr.count;i++)
    {
        NSLog(@" x[%d] is %f  ",i,[xValueArr[i] floatValue]);
        NSLog(@" y[%d] is %f  ",i,[yValueArr[i] floatValue]);
    }
    NSLog(@"--------------point is %f %f",chartView.frame.origin.x,chartView.frame.origin.y);

    NSLog(@"--------------window is %f,%f",_height,_width);
    */
    
    CGRect viewBounds = self.view.frame;
    viewBounds.origin.y = 0;
    viewBounds.size.height = 460;
    self.pg = [[UIPageControl alloc]initWithFrame:CGRectMake(viewBounds.origin.x, viewBounds.origin.y, viewBounds.size.width,60)];
    
    AppDelegate *appDelegate= [[UIApplication sharedApplication]delegate];
     
    self.pg.alpha = 1;
    self.pg.numberOfPages = appDelegate.citys.count;
    if (self.selectedCityName) {
        for (int i = 0; i<appDelegate.citys.count; i++) {
            if ([self.selectedCityName isEqualToString:appDelegate.citys[i]]) {
                self.pg.currentPage = i;
            }
    }
    
    }
    else
    self.pg.currentPage = self.pg.numberOfPages - 1;

    // self.pg.pageIndicatorTintColor = [UIColor purpleColor];//点点的颜色(不是当前页的点的颜色)
    self.pg.currentPageIndicatorTintColor = [UIColor whiteColor];//点点的颜色(当前页的点的颜色)
    
    //scrollview控制大小的地方
    //滚动图里的表格
    self.tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, _height, _width,_height*3)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorColor = [UIColor colorWithWhite:1 alpha:0.0];
    self.tableView.pagingEnabled = YES;
 
    [self.scrollView addSubview:self.tableView];
    self.weatherCurrentData.tempLow=[NSNumber numberWithFloat:minTem];
    self.weatherCurrentData.tempHigh=[NSNumber numberWithFloat:maxTem];
    //城市名称
    self.cityname = [[UILabel alloc]init];
    self.cityname.font = [UIFont fontWithName:nil size:20];
    self.cityname.textColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.cityname];
    [self.cityname mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.scrollView.mas_centerX);
        make.top.equalTo(self.scrollView.mas_top).with.offset(35);
    }];
    
    self.weatherImage  =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"weather-moon"]];
    self.weatherImage.frame  = CGRectMake(10, 60, 20, 20);
  
    [self.scrollView addSubview:self.weatherImage];
      //，这边如果放开注释，就会报错
    
    /*
     [self.weatherImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView.mas_left).with.offset(70);
        make.bottom.equalTo(self.scrollView.mas_top).with.offset(-269);
        make.height.equalTo(@30);
        make.width.equalTo(@30);
    }];
    */
    //晴，多云等
    self.weatherLabel =[[UILabel alloc]init];
    [self.scrollView addSubview:self.weatherLabel];
    self.weatherLabel.font=[UIFont fontWithName:nil size:15];
    self.weatherLabel.textColor=[UIColor whiteColor];
    
    [self.weatherLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.weatherImage.mas_centerY);
        make.left.equalTo(self.weatherImage.mas_right).with.offset(8);
    }];
    self.currentTempretureLabel =[[UILabel alloc]init];
    self.currentTempretureLabel.font=[UIFont fontWithName:@"HelveticaNeue-UltraLight" size:100];
    self.currentTempretureLabel.textColor=[UIColor whiteColor];
    
    [self.scrollView addSubview:self.currentTempretureLabel];
    [self.currentTempretureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.scrollView.mas_centerX);
        make.top.equalTo(self.scrollView.mas_top).with.offset(60);
    }];
    self.tempretureRangeLabel =[[UILabel alloc]init];
    self.tempretureRangeLabel.font=[UIFont fontWithName:@"HelveticaNeue-UltraLight" size:20];
    self.tempretureRangeLabel.textColor=[UIColor whiteColor];
    
   
    [self.scrollView addSubview:self.tempretureRangeLabel];
    [self.tempretureRangeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.currentTempretureLabel.mas_bottom).with.offset(10);
        make.right.equalTo(self.currentTempretureLabel.mas_right);
        
    }];
   //放在scrollview上面就
   UITabBar  *tbar= [[UITabBar alloc]init];
    //tbar.backgroundColor = [UIColor whiteColor];
    tbar.backgroundColor = [UIColor clearColor];
    [tbar setFrame:CGRectMake(0, 430, _width, _height)];
    [tbar setDelegate:self];
    
    UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:@"城市列表" image:nil tag:0];
    UITabBarItem * tabBarItem2 = [[UITabBarItem alloc] initWithTitle:@"定位" image:nil tag:1];
    UITabBarItem * tabBarItem3 = [[UITabBarItem alloc] initWithTitle:@"管理城市" image:nil tag:2];
    NSArray *tabBarItemArray = [[NSArray alloc] initWithObjects: tabBarItem1, tabBarItem2, tabBarItem3, nil];
    [tbar setItems: tabBarItemArray];
    [self.scrollView addSubview:self.pg];
    [self.scrollView addSubview:tbar]; //如果放在scrollview上面就很好
    [self setTheCurrentMessage:self.weatherCurrentData];
}

#pragma  mark - setImmediatelyInformation
-(void)setTheCurrentMessage:(CurrentWeatherData *)data
{
    self.cityname.text = data.locationName;
    self.weatherLabel.text=data.conditionDescription;
    self.currentTempretureLabel.text=[NSString stringWithFormat:@"%.fº",[data.temperature floatValue]];
    self.tempretureRangeLabel.text=[NSString stringWithFormat:@"%.fº-%.fº",[data.tempLow floatValue],[data.tempHigh floatValue]];
    
    UIImageView *weatherImage1 =[[UIImageView alloc]initWithImage:[UIImage imageNamed:data.icon]];
    self.weatherImage =  weatherImage1;
   [self addTimer]; // 暂时先不开启。。。晃眼
}

#pragma  mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.hoursTempreture.count+1;
    }else if(section == 1){
        return 8;
    }
    else{
        return 8;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
    if (! cell) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:Cell];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.conditionLabel.textColor = [UIColor whiteColor];
    cell.TimeLabel.textColor = [UIColor whiteColor];
    cell.tempLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.1];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.detailTextLabel.textColor = [UIColor whiteColor];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.conditionLabel.text = nil;
            cell.TimeLabel.text = nil;
            cell.tempLabel.text = nil;
            NSString *dateStr = [OpenWeatherMapInterface getDay];
            [self configureHeaderCell:cell title:dateStr];
        }
        else {
            cell.imageView.image =[UIImage imageNamed:[self.hoursTempreture[indexPath.row-1] valueForKey:@"icon"]];
            cell.TimeLabel.text = [NSString stringWithFormat:@"%@ %@",  [[[self.hoursTempreture[indexPath.row-1] valueForKey:@"date"] substringFromIndex:11] substringToIndex:2],[self.hoursTempreture[indexPath.row-1] valueForKey:@"hour"]];
            cell.tempLabel.text =[NSString stringWithFormat:@"%d℃",[[self.hoursTempreture[indexPath.row-1] valueForKey:@"temperature"] intValue]];
            cell.conditionLabel.text = [self.hoursTempreture[indexPath.row-1] valueForKey:@"condition"];
        }
    }
    else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.conditionLabel.text = nil;
            cell.TimeLabel.text = nil;
            cell.tempLabel.text = nil;
            [self configureHeaderCell:cell title:@"多天天气"];
        }
        else {
            
            int tempHigh = [[self.daysTempreture[indexPath.row-1] tempHigh] intValue];
            int tempLow = [[self.daysTempreture[indexPath.row-1] tempLow] intValue];
            NSString *icon1 = [self.daysTempreture[indexPath.row-1] icon];
            cell.imageView.image =[UIImage imageNamed:icon1];
            cell.tempLabel.text = [NSString stringWithFormat:@"%d/%d℃",tempHigh,tempLow];
            if(indexPath.row == 1)
                cell.TimeLabel.text = @"今天";
            else
             cell.TimeLabel.text = [self.daysTempreture[indexPath.row-1] valueForKey:@"weekDay"];
            cell.conditionLabel.text = [self.daysTempreture[indexPath.row-1] valueForKey:@"condition"];
        }
    }
    else if(indexPath.section == 2)
    {
        int tempHigh = [[self.daysTempreture[indexPath.row-1+7] tempHigh] intValue];
        int tempLow = [[self.daysTempreture[indexPath.row-1+7] tempLow] intValue];
        NSString *icon1 = [self.daysTempreture[indexPath.row-1+7] icon];
        cell.imageView.image =[UIImage imageNamed:icon1];
        cell.tempLabel.text = [NSString stringWithFormat:@"%d/%d℃",tempHigh,tempLow];
        cell.TimeLabel.text = [self.daysTempreture[indexPath.row-1+7] valueForKey:@"weekDay"];
        cell.conditionLabel.text = [self.daysTempreture[indexPath.row-1+7] valueForKey:@"condition"];
    }
    return cell;
    
    
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger cellCount = [self tableView:tableView numberOfRowsInSection:indexPath.section];
    return _height / ((CGFloat)cellCount);
}

- (void)configureHeaderCell:(UITableViewCell *)cell title:(NSString *)title {
    cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
    cell.textLabel.text = title;
    cell.detailTextLabel.text = @"";
    cell.imageView.image = nil;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat height = scrollView.bounds.size.height;
    CGFloat position = MAX(scrollView.contentOffset.y, 0.0);
    CGFloat percent = MIN(position / height, 1.0);
    self.blurredView.alpha = percent;
}

-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"ade0c46e82a50e4d21ba134779d94254" forHTTPHeaderField: @"apikey"];
    
    NSURLResponse *res = [[NSURLResponse alloc]init];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:nil];
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    self.cityName =[dict[@"retData"] objectForKey:@"city"];
    
}
static int i = 0;

//开启定时器
-(void)addTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
}

//关闭定时器
-(void)removeTimer{
    [self.timer invalidate];
}
//切换下一幅背景图
-(void)nextImage
{
    UIImage *backgroundImage;
    if(i == 0)
    {
        backgroundImage  = [UIImage imageNamed:@"bg11.jpg"];
        //NSLog(@"in i =0 ");
    }
    if (i==1) {
        backgroundImage = [UIImage imageNamed:@"bg22.jpg"];
        //NSLog(@"in i =1 ");
        
    }
    if (i==2) {
        backgroundImage = [UIImage imageNamed:@"bg55.jpg"];
        i=-1;
        //NSLog(@"in i =2 ");
        
    }
    i++;
    //--------------虽然实现了，但是对于一些参数的改变还是显得没有生效，没有那么顺手好用啊
    CATransition *animation = [CATransition animation];
    [animation setDuration:1.25f];
    //[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    //[animation setType:kCATransitionReveal];
    //[animation setType:kCAEmitterBehaviorDrag];
    [animation setType:kCAEmitterBehaviorColorOverLife];
    
    [animation setSubtype: kCATransitionFromBottom];
    self.backGround.image = backgroundImage;
    [self.view.layer addAnimation:animation forKey:@"Reveal"];
    [self.blurredView setImageToBlur:backgroundImage blurRadius:10 completionBlock:nil];
}


@end
